package cn.intertion.controller;

import cn.intertion.model.wxObj;
import cn.intertion.service.WXService;
import cn.intertion.service.WxToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping(value = "/wx")
public class WXController {

    @RequestMapping(value = "/test")
    public String test(Model model, HttpServletRequest req) throws Exception {
        model.addAttribute("msg", "短信验证码错误。");
        return "mesg.html";
    }

    private static final Logger log = LoggerFactory.getLogger(WXController.class);

    @Autowired
    private WXService wxService;

    @Autowired
    private WxToken wxToken;

    @Value("${returnmessage}")
    private String message;

    //微信绑定手机号
    @RequestMapping(value = "/bindWX")
    public String bindWX(Model model, HttpServletRequest req) throws Exception {

        String b = wxService.bindWX(req);

        if (b.equals("-5")) {
            model.addAttribute("msg", "短信验证码错误。");
            return "mesg.html";
        }

        if (b.equals("1")) {
            model.addAttribute("msg", "该号码没有账户注册，请换个号码重试。或者联系管理员 电话：" + message.split("%")[0] + "邮箱：" + message.split("%")[1]);
            return "mesg.html";
        }
        if (b.startsWith("2#")) {
            model.addAttribute("token", b.split("#")[1]);
            model.addAttribute("ip", wxObj.wxip);
            model.addAttribute("ip2", wxObj.wxip);
            return "mobile.html";
        }
        model.addAttribute("msg", "发生未知错误，");
        return "mesg.html";
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "/c")
    public String reg(Model model, HttpServletRequest req) throws Exception {

        String s = wxService.addUser(req);
        if ("-1".equals(s)) {
            model.addAttribute("msg", "短信验证码错误。");
            return "mesg.html";
        }
        if ("-12".equals(s)) {
            model.addAttribute("msg", "短信验证码错误。");
            return "mesg.html";
        }
        if ("-3".equals(s)) {
            model.addAttribute("msg", "该账号已注册。");
            return "mesg.html";
        }
        if ("-2".equals(s)) {
            model.addAttribute("msg", "未知异常。");
            return "mesg.html";
        }
        model.addAttribute("token", s);
        model.addAttribute("ip", wxObj.wxip);
        return "mobile.html";

    }


    /**
     * 用户注册或绑定手机号
     */
    @RequestMapping(value = "/roa")
    public String regOrAdd(Model model, HttpServletRequest req) throws Exception {

        String s = wxService.regOrAdd(req);
        if ("-9".equals(s)) {
            model.addAttribute("msg", "请填写公司船舶名。");
            return "mesg.html";
        }
        if ("-12".equals(s)) {
            model.addAttribute("msg", "短信验证码错误。");
            return "mesg.html";
        }
        if ("-2".equals(s)) {
            model.addAttribute("msg", "未知异常。");
            return "mesg.html";
        }
        if ("-7".equals(s)) {
            model.addAttribute("msg", "未知异常。");
            return "mesg.html";
        }
        model.addAttribute("token", s);
        model.addAttribute("ip", wxObj.wxip);
        return "mobile.html";

    }


    @RequestMapping(value = "/login")
    public String login(Model model, @RequestParam("code") String code, @RequestParam("state") String state) throws Exception {
        String result = wxService.login(code, state);
        if (result.equals("-11")) {
            model.addAttribute("msg", "非岸端人员不能在微信上登陆。请重新绑定账户。若有疑问请联系管理员电话："
                    + message.split("%")[0] + "邮箱：" + message.split("%")[1]);
            return "mesg.html";
        }
        if (result.startsWith("0#")) {
            model.addAttribute("token", result.split("#")[1]);
            model.addAttribute("ip", wxObj.wxip);
            return "mobile.html";
        }
        if (result.equals("-1") || result.equals("-2")) {
            model.addAttribute("msg", "发生未知异常。");
            return "err.html";
        }
        model.addAttribute("msg", "发生未知异常。");
        return "mesg.html";
    }


    /**
     * 发送短信
     */
    @RequestMapping(value = "/sm")
    @ResponseBody
    public String sendShortmessage(@RequestParam("p") String p) throws Exception {
        return wxService.sendShortmessage(p);
    }

    /**
     * 短信验证码校验
     */
    @RequestMapping("/cdx")
    @ResponseBody
    public String check3(@RequestParam("p") String p, @RequestParam("d") String d) throws Exception {
        return wxService.check3(p.trim() + d.trim());
    }


    /**
     * 获取验证码（静态）
     */
    @RequestMapping("/getPicCode")
    public void captcha(@RequestParam("uid") String uid, HttpServletResponse resp) throws Exception {
        wxService.out2(uid, resp);
    }

    //获取动态验证码
    @RequestMapping("/getPicCode2")
    public void captcha2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String uid = request.getParameter("uid");
        wxService.out(130, 48, 5, request, response, uid);
    }

    /**
     * 静态验证码校验
     */
    @RequestMapping("/check")
    @ResponseBody
    public String check(@RequestParam("uid") String uid, @RequestParam("code") String code) {
        Integer i = wxService.check2(uid.trim() + code.trim().toLowerCase());
        return "" + i;
    }

    //  动态验证码校验
    @RequestMapping("/check2")
    @ResponseBody
    public String check2(@RequestParam("uid") String uid, @RequestParam("code") String code) {

        Integer i = wxService.check(uid.trim() + code.trim());
        return "" + i;
    }

    /**
     * 获取jssdk签名
     */
    @RequestMapping("/getJsSdkTicket")
    @ResponseBody
    public String getJsSdkTicket(@RequestParam("t") String t) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        return wxService.getJsSdkTicket(t);
    }

    @RequestMapping(value = "/checkUser")
    @ResponseBody
    public String checkUser(@RequestParam("name") String name, @RequestParam("pswd") String pswd) {
        if (wxService.checkUser(name, pswd)) return "0";
        return "1";
    }

    @RequestMapping(value = "/zz")
    @ResponseBody
    public String test() {
        return "1";
    }

    @RequestMapping(value = "/gwt")
    @ResponseBody
    public String getWeiXinToken() throws Exception {
        long l = wxObj.tokenDate;
        long ll = System.currentTimeMillis() - l;
        if (ll > ((long) 30 * 60 * 1000) && l != 0) {
            log.error("accesstoken 过期，重新申请！！");
            wxToken.setWXAccessToken();
        } else {
            log.error("accesstoken 没有过期");
        }
        if (!wxObj.accessToken.equals("")) return wxObj.accessToken;

        return "-1";
    }
}
